package com.example.cardgame_1

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.GridLayoutManager
import com.example.cardgame.model.CardMatchingGame

class ThirdActivity : AppCompatActivity() {
    private val game: CardMatchingGame = CardMatchingGame(24)
    private lateinit var adapter: CardAdapter

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 使用正确的布局文件
        setContentView(R.layout.activity_third)

        val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
        adapter = CardAdapter(game)
        recyclerView.adapter = adapter

        // 根据屏幕方向设置网格布局
        val configure = resources.configuration
        recyclerView.layoutManager = if (configure.orientation == Configuration.ORIENTATION_PORTRAIT) {
            GridLayoutManager(this, 4)
        } else {
            GridLayoutManager(this, 6)
        }

        // 卡牌点击事件
        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()
        }

        // 初始化UI
        updateUI()

        // 重置按钮
        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            game.reset()
            updateUI()
        }

        // 返回按钮
        val back = findViewById<Button>(R.id.button_back)
        back.setOnClickListener {
            finish()
        }
    }

    // 更新UI显示
    private fun updateUI(){
        adapter.notifyDataSetChanged()
        val score = findViewById<TextView>(R.id.textView)
        score.text = getString(R.string.score) + game.score.toString()
    }
}